<template>
  <div id="box">
    <p>IntersectionObserver懒加载</p>
    <img v-for="(image, i) in images" :key="i" src :data-img-url="image" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      images: [
        'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1574247890587&di=88d4066be3d57ac962a6bec37e265d37&imgtype=0&src=http%3A%2F%2F01.imgmini.eastday.com%2Fmobile%2F20170810%2F20170810151144_d41d8cd98f00b204e9800998ecf8427e_3.jpeg',
        'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=4054762707,1853885380&fm=26&gp=0.jpg',
        'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1574247912077&di=508a949e5e291875debf6ca844292cd4&imgtype=0&src=http%3A%2F%2F03imgmini.eastday.com%2Fmobile%2F20180827%2F20180827095359_6759372e9bd28026ee6f53b500fb4291_2.jpeg'
      ]
    };
  },
  mounted() {
    const box = document.querySelector('#box');
    const images = document.querySelectorAll('img');

    const observerLazyLoad = new IntersectionObserver(
      entries => {
        entries.forEach(item => {
          if (item.isIntersecting) {
            item.target.src = item.target.dataset.imgUrl;
          }
        });
      },
      {
        root: box, // 父级元素
        rootMargin: '20px 0px 100px 0px' // 设置偏移 我们可以设置在目标元素距离底部100px的时候发送请求
      }
    );

    images.forEach(image => {
      observerLazyLoad.observe(image);
    });
  }
};
</script>

<style lang="scss" scoped>
img {
  display: block;
  height: 500px;
  margin: 30px;
}
</style>
